﻿using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace Kovan.Library.Utils
{
    /// <summary>
    /// Request 操作类
    /// </summary>
    public class KRequest
    {
        #region 请求方式判断
        /// <summary>
        /// 判断当前页面是否接收到了Post请求
        /// </summary>
        /// <returns>是否接收到了Post请求</returns>
        public static bool IsPost()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("POST");
        }
        /// <summary>
        /// 判断当前页面是否接收到了Get请求
        /// </summary>
        /// <returns>是否接收到了Get请求</returns>
        public static bool IsGet()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("GET");
        }
        /// <summary>
        /// 判断当前请求是否是来源本网
        /// </summary>
        /// <returns></returns>
        public static bool IsLocalRequest()
        {
            Uri ComeUrl = HttpContext.Current.Request.UrlReferrer;//取得来访URl源
            string cUrl;
            if (ComeUrl == null)
            {
                return false;
            }
            else
            {
                string reffer = ComeUrl.ToString();
                cUrl = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"];

                if (reffer.Substring(cUrl.Length, 1) == ":")
                {
                    cUrl += ":" + HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString();
                }
                int lenth;
                lenth = cUrl.Length;
                cUrl += HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"];
                int result;
                result = String.Compare(reffer, 1, cUrl, 1, lenth, true);
                return (result == 0);
            }
        }
        #endregion


        #region 获取网络文件内容等方法
        /// <summary>
        /// 使用系统默认编码获取某个网页的内容
        /// </summary>
        /// <param name="url">网页地址</param>
        public static string GetUrlContent(string url)
        {
            return GetUrlContent(url, System.Text.Encoding.Default);
        }
        /// <summary>
        /// 使用指定的编码获取某个网页的内容
        /// </summary>
        /// <param name="url">网页地址</param>
        /// <param name="encoding">编码</param>
        public static string GetUrlContent(string url, System.Text.Encoding encoding)
        {
            return GetUrlContent(url, encoding, null);
        }
        /// <summary>
        /// 使用指定的编码获取某个网页的内容
        /// </summary>
        /// <param name="url">网页地址</param>
        /// <param name="encoding">编码</param>
        /// <param name="referer">Referer 标头值</param>
        public static string GetUrlContent(string url, System.Text.Encoding encoding, string referer)
        {
            return GetUrlContent(url, encoding, referer, null);
        }
        /// <summary>
        /// 获取某个网页的内容
        /// </summary>
        /// <param name="url">网页地址</param>
        /// <param name="encoding">编码</param>
        /// <param name="referer">Referer 标头值</param>
        /// <param name="proxy">代理设置</param>
        public static string GetUrlContent(string url, System.Text.Encoding encoding, string referer, WebProxy proxy)
        {
            HttpWebResponse webResponse = (HttpWebResponse)GetWebResponse(url, referer, proxy);
            if (webResponse != null)
            {
                try
                {
                    System.IO.Stream stream = webResponse.GetResponseStream();
                    System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, encoding);
                    System.Text.StringBuilder content = new System.Text.StringBuilder();
                    char[] buffer = new char[1024];
                    int l;
                    do
                    {
                        l = streamReader.Read(buffer, 0, buffer.Length);
                        if (l > 0)
                            content.Append(new String(buffer));
                    }
                    while (l > 0);
                    streamReader.Close();
                    webResponse.Close();
                    return content.ToString();
                }
                catch
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }


        private static WebResponse GetWebResponse(string url, string referer, WebProxy proxy)
        {
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                if (referer != null)
                    webRequest.Referer = referer;
                if (proxy != null)
                    webRequest.Proxy = proxy;
                WebResponse response = webRequest.GetResponse();
                return response;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region 获取参数
        /// <summary>
        /// 返回指定的服务器变量信息
        /// </summary>
        /// <param name="strName">服务器变量名</param>
        /// <returns>服务器变量信息</returns>
        public static string GetServerString(string strName)
        {
            return KConvert.ToString(HttpContext.Current.Request.ServerVariables[strName]);
        }

        /// <summary>
        /// 返回上一个页面的地址
        /// </summary>
        /// <returns>上一个页面的地址</returns>
        public static string GetUrlReferrer()
        {
            string retVal = null;

            try
            {
                retVal = HttpContext.Current.Request.UrlReferrer.ToString();
            }
            catch { }

            if (retVal == null)
                return "";

            return retVal;

        }

        /// <summary>
        /// 得到当前完整主机头
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentFullHost()
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            if (!request.Url.IsDefaultPort)
            {
                return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
            }
            return request.Url.Host;
        }


        /// <summary>
        /// 得到主机头
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            return HttpContext.Current.Request.Url.Host;
        }


        /// <summary>
        /// 获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在))
        /// </summary>
        /// <returns>原始 URL</returns>
        public static string GetRawUrl()
        {
            return HttpContext.Current.Request.RawUrl;
        }

        /// <summary>
        /// 判断当前访问是否来自浏览器软件
        /// </summary>
        /// <returns>当前访问是否来自浏览器软件</returns>
        public static bool IsBrowserGet()
        {
            string[] BrowserName = { "ie", "opera", "netscape", "mozilla" };
            string curBrowser = HttpContext.Current.Request.Browser.Type.ToLower();
            for (int i = 0; i < BrowserName.Length; i++)
            {
                if (curBrowser.IndexOf(BrowserName[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 判断是否是刷新页面
        /// </summary>
        /// <returns></returns>
        public static bool IsRefresh(string randomCode)
        {
            string ip = KRequest.GetIP();
            HttpCookie cookie = HttpContext.Current.Request.Cookies["skyhootrack"];
            if (cookie == null)
                cookie = new HttpCookie("skyhootrack");
            string name = KConvert.ToString(ip + randomCode).GetHashCode().ToString();
            if (KConvert.IsEmpty(cookie.Values[name]))
            {
                if (cookie.Values.Count > 19)
                    cookie.Values.Remove(cookie.Values.Keys[0]);
                cookie.Values.Add(name, "0");
                HttpContext.Current.Response.AppendCookie(cookie);
                return false;
            }
            else
                return true;
        }

        /// <summary>
        /// 判断是否来自搜索引擎链接
        /// </summary>
        /// <returns>是否来自搜索引擎链接</returns>
        public static bool IsSearchEnginesGet()
        {
            string[] SearchEngine = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom" };
            string tmpReferrer = KRequest.GetUrlReferrer().ToLower();
            for (int i = 0; i < SearchEngine.Length; i++)
            {
                if (tmpReferrer.IndexOf(SearchEngine[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获得当前完整Url地址
        /// </summary>
        /// <returns>当前完整Url地址</returns>
        public static string GetUrl()
        {
            return HttpContext.Current.Request.Url.ToString();
        }


        /// <summary>
        /// 获得指定Url参数的值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的值</returns>
        public static string GetQueryString(string strName)
        {
            return KConvert.ToString(HttpContext.Current.Request.QueryString[strName]);
        }

        /// <summary>
        /// 获得当前页面的名称
        /// </summary>
        /// <returns>当前页面的名称</returns>
        public static string GetPageName()
        {
            string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
            return urlArr[urlArr.Length - 1];
        }

        /// <summary>
        /// 返回表单或Url参数的总个数
        /// </summary>
        /// <returns></returns>
        public static int GetParamCount()
        {
            return HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count;
        }


        /// <summary>
        /// 获得指定表单参数的值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>表单参数的值</returns>
        public static string GetFormString(string strName)
        {
            return KConvert.ToString(HttpContext.Current.Request.Form[strName]);
        }

        /// <summary>
        /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">参数</param>
        /// <returns>Url或表单参数的值</returns>
        public static string GetString(string strName)
        {
            if ("".Equals(GetQueryString(strName)))
            {
                return GetFormString(strName);
            }
            else
            {
                return GetQueryString(strName);
            }
        }


        /// <summary>
        /// 获得指定Url参数的int类型值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url参数的int类型值</returns>
        public static int GetQueryInt(string strName, int defValue)
        {
            return KConvert.ToInt(HttpContext.Current.Request.QueryString[strName], defValue);
        }


        /// <summary>
        /// 获得指定表单参数的int类型值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>表单参数的int类型值</returns>
        public static int GetFormInt(string strName, int defValue)
        {
            return KConvert.ToInt(HttpContext.Current.Request.Form[strName], defValue);
        }

        /// <summary>
        /// 获得指定Url或表单参数的int类型值, 先判断Url参数是否为缺省值, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">Url或表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url或表单参数的int类型值</returns>
        public static int GetInt(string strName, int defValue)
        {
            if (GetQueryInt(strName, defValue) == defValue)
            {
                return GetFormInt(strName, defValue);
            }
            else
            {
                return GetQueryInt(strName, defValue);
            }
        }

        /// <summary>
        /// 获得指定Url参数的float类型值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url参数的int类型值</returns>
        public static float GetQueryFloat(string strName, float defValue)
        {
            return KConvert.ToSingle(HttpContext.Current.Request.QueryString[strName], defValue);
        }
        /// <summary>
        /// 获得指定表单参数的float类型值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>表单参数的float类型值</returns>
        public static float GetFormFloat(string strName, float defValue)
        {
            return KConvert.ToSingle(HttpContext.Current.Request.Form[strName], defValue);
        }

        /// <summary>
        /// 获得指定Url或表单参数的float类型值, 先判断Url参数是否为缺省值, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">Url或表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url或表单参数的int类型值</returns>
        public static float GetFloat(string strName, float defValue)
        {
            if (GetQueryFloat(strName, defValue) == defValue)
            {
                return GetFormFloat(strName, defValue);
            }
            else
            {
                return GetQueryFloat(strName, defValue);
            }
        }

        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {

            string result = String.Empty;

            result = GetServerString("HTTP_X_FORWARDED_FOR");
            if (null == result || result == String.Empty)
            {
                result = GetServerString("REMOTE_ADDR");
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }

            if (null == result || result == String.Empty || !KConvert.IsIPV4(result))
            {
                return "0.0.0.0";
            }

            return result;

        }

        /// <summary>
        /// 获取客户端公网IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetUserIP()
        {

            return HttpContext.Current.Request.UserHostAddress;

            //string result = String.Empty;
            //result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            //if (result != null && result != String.Empty)
            //{
            //    //可能有代理 
            //    if (result.IndexOf(".") == -1)     //没有“.”肯定是非IPv4格式 
            //        result = null;
            //    else
            //    {
            //        if (result.IndexOf(",") != -1)
            //        {
            //            //有“,”，估计多个代理。取第一个不是内网的IP。 
            //            result = result.Replace(" ", "").Replace("'", "");
            //            string[] temparyip = result.Split(",;".ToCharArray());
            //            for (int i = 0; i < temparyip.Length; i++)
            //            {
            //                if (IsIPAddress(temparyip[i])
            //                    && temparyip[i].Substring(0, 3) != "10."
            //                    && temparyip[i].Substring(0, 7) != "192.168"
            //                    && temparyip[i].Substring(0, 7) != "172.16.")
            //                {
            //                    return temparyip[i];     //找到不是内网的地址 
            //                }
            //            }
            //        }
            //        else if (IsIPAddress(result)) //代理即是IP格式 
            //            return result;
            //        else
            //            result = null;     //代理中的内容 非IP，取IP 
            //    }
            //}
            //string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            //if (null == result || result == String.Empty)
            //    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            //if (result == null || result == String.Empty)
            //    result = HttpContext.Current.Request.UserHostAddress;

            //return result;













            //string tempip = "";
            //try
            //{
            //    WebRequest wr = WebRequest.Create("http://city.ip138.com/city1.asp");
            //    using (Stream s = wr.GetResponse().GetResponseStream())
            //    {
            //        using (StreamReader sr = new StreamReader(s, Encoding.Default))
            //        {
            //            string all = sr.ReadToEnd(); //读取网站的数据

            //            int start = all.IndexOf("[") + 1;
            //            int end = all.IndexOf("]", start);
            //            tempip = all.Substring(start, end - start);
            //        }
            //    }
            //}
            //catch
            //{
            //    tempip = HttpContext.Current.Request.UserHostAddress;
            //}
            //return tempip;


            //string str = null;
            //string url = "http://city.ip138.com/city1.asp";
            //WebClient wc = new WebClient();
            //wc.Credentials = CredentialCache.DefaultCredentials;
            //Byte[] pageData = wc.DownloadData(url);
            //string MyUrl = System.Text.Encoding.UTF8.GetString(pageData);
            //int start = MyUrl.IndexOf("[") + 1;
            //int end = MyUrl.IndexOf("]", start);
            //str = MyUrl.Substring(start, end - start);
            //return str;



            //string act = "ip";
            //string ip = string.Empty;
            //if (act == "ip")
            //{
            //    if (HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null)
            //    {
            //        ip = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
            //    }
            //    else if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            //    {
            //        ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            //    }
            //    else
            //    {
            //        ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            //    }
            //    return ip;
            //}
            //else
            //{
            //    return ip;
            //}




            //string ip = string.Empty;
            //HttpRequest request = HttpContext.Current.Request;
            //if (request.ServerVariables["HTTP_VIA"] != null)
            //{
            //    ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
            //}
            //else
            //{
            //    ip = request.UserHostAddress;
            //}

            //return ip;





            //string ip;
            //string[] temp;
            //bool isErr = false;
            //if (HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"] == null)
            //    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            //else
            //    ip = HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"].ToString();
            //if (ip.Length > 15)
            //    isErr = true;
            //else
            //{
            //    temp = ip.Split('.');
            //    if (temp.Length == 4)
            //    {
            //        for (int i = 0; i < temp.Length; i++)
            //        {
            //            if (temp[i].Length > 3) isErr = true;
            //        }
            //    }
            //    else
            //        isErr = true;
            //}

            //if (isErr)
            //    return "1.1.1.1";
            //else
            //    return ip;

        }

        //// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        /// <param name="str1">待判断的IP地址</param>
        /// <returns>true or false</returns>
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }

        /// <summary>
        /// 获取网站相对路径
        /// </summary>
        public static string SitePath
        {
            get
            {
                string path = HttpContext.Current.Request.ApplicationPath;
                if (path.EndsWith("/"))
                    return path;
                return path + "/";
            }
        }

        #endregion
    }
}
